package com.xgpro.pc.studycentre.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.service.BaseService;
import com.xgpro.common.utils.*;
import com.xgpro.domain.studycentre.entity.Course;
import com.xgpro.domain.studycentre.entity.CourseEVA;
import com.xgpro.domain.studycentre.entity.UserCourse;
import com.xgpro.domain.studycentre.vo.*;
import com.xgpro.domain.talentintroduction.entity.Attachment;
import com.xgpro.domain.talentintroduction.entity.User;
import com.xgpro.mapper.studycentre.AttachmentMapper;
import com.xgpro.mapper.studycentre.CourseEvaMapper;
import com.xgpro.mapper.studycentre.CourseMapper;
import com.xgpro.mapper.studycentre.UserCourseMapper;
import com.xgpro.mapper.talentintroduction.UserMapper;
import com.xgpro.pc.studycentre.service.CoursePCService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author tx
 * @version 1.0
 * @date 2019/10/14 20:55
 */
@Service
@Transactional(readOnly = false)
public class CoursePCServiceImpl  extends BaseService implements CoursePCService {
    /**
     * 内部课程
     */
    private final static Integer COURSETYPE=0;

    /**
     * 公司管理员
     */
    private final static Integer COMPANYROLE=1;

    /**
     * 部门管理员
     */
    private final static Integer DEPTROLE=2;

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AttachmentMapper attachmentMapper;

    @Resource
    private DeptmentUtil deptmentUtil;
    /**
     * 查询课程信息待审批
     * @param coursePCFront
     * @return
     */
    @Override
    public CoursePCResult qryCoursePCResult(CoursePCFront coursePCFront,List<Integer> roleIds,Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        Integer deptId = user.getDeptId();
        Integer secondDeptId = user.getSecondDeptId();
        Set<Integer> childDeptIds = deptmentUtil.getChildDeptIds(new HashSet<Integer>(), secondDeptId);
        List<Integer> deptIds = new ArrayList<>();
        for (Integer childDeptId : childDeptIds) {
            deptIds.add(childDeptId);
        }
        Example example = new Example(Course.class);
        Example.Criteria criteria = example.createCriteria();
        if(coursePCFront.getTitle()!=null&&!"".equals(coursePCFront.getTitle())){
            criteria.andLike("title","%"+coursePCFront.getTitle()+"%");
        }
        if(coursePCFront.getUsername()!=null&&!"".equals(coursePCFront.getUsername())){
            criteria.andLike("teaUsername","%"+coursePCFront.getUsername()+"%");
        }
        if(coursePCFront.getCourseDept()!=null&&!"".equals(coursePCFront.getCourseDept())){
            criteria.andEqualTo("courseDept",coursePCFront.getCourseDept());
        }
        criteria.andEqualTo("courseType",COURSETYPE);
        Integer flag=0;
        Integer count=0;
        for (Integer roleId : roleIds) {
            if(roleId.equals(COMPANYROLE)){
                flag=1;
                count++;
                //公司管理员
            }
            if(roleId.equals(DEPTROLE)){
                flag=2;
                count++;
                //部门管理员
            }
        }
        if(count.equals(2)){
            ArrayList arrayList = new ArrayList();
            arrayList.add(0);
            arrayList.add(3);
            //双重角色
            criteria.andIn("status",arrayList);
        }else{
            if(flag.equals(1)){
                criteria.andEqualTo("status",3);
            }
            if(flag.equals(2)){
                criteria.andIn("deptId",deptIds);
                criteria.andEqualTo("status",0);
            }
        }
        //排序
        example.setOrderByClause("update_time DESC");
        PageHelper.startPage(coursePCFront.getPage(),coursePCFront.getPageSize());
        Page<Course> pages =(Page<Course>)courseMapper.selectByExample(example);
        List<Course> courses = pages.getResult();
        CoursePCResult coursePCResult = new CoursePCResult();
        CoursePCBack coursePCBack=null;
        List<CoursePCBack> coursePCBacks = coursePCResult.getCoursePCBackList();
        int totals=0;
        if(courses!=null&&courses.size()>0){
            //coursePCResult.setTotals(pages.getTotal());
            for (Course cours : courses) {
                if(!deptIds.contains(cours.getDeptId())&&cours.getStatus().equals(0)){
                    continue;
                }
                        coursePCBack=new CoursePCBack();
                        coursePCBack.setId(cours.getId());
                        coursePCBack.setTitle(cours.getTitle());
                        coursePCBack.setFlag(cours.getFlag());
                        coursePCBack.setNum(cours.getNum());
                        coursePCBack.setCourseDept(cours.getCourseDept());
                        coursePCBack.setUsername(cours.getTeaUsername());
                        coursePCBacks.add(coursePCBack);
                        totals++;
                }
            }
            coursePCResult.setTotals(totals);
        return coursePCResult;
    }

    /**
     * 查询授课完毕课程
     * @param coursePCFront
     * @param roIds
     * @return
     */
    @Override
    public CoursePCResult qryOverCoursePCResult(CoursePCFront coursePCFront, List<Integer> roIds) {
        Integer flag=0;
        for (Integer roId : roIds) {
            if(COMPANYROLE.equals(roId)){
                flag=1;
                break;
            }
        }
        if(!flag.equals(1)){
            throw new BusinessRuntimeException(ResultCodeEnum.CAN_NO_TO_VIS.getCode(),ResultCodeEnum.CAN_NO_TO_VIS.getMessage());
        }
        Example example = new Example(Course.class);
        Example.Criteria criteria = example.createCriteria();
        if(coursePCFront.getTitle()!=null&&!"".equals(coursePCFront.getTitle())){
            criteria.andLike("title","%"+coursePCFront.getTitle()+"%");
        }
        if(coursePCFront.getUsername()!=null&&!"".equals(coursePCFront.getUsername())){
            criteria.andLike("teaUsername","%"+coursePCFront.getUsername()+"%");
        }
        if(coursePCFront.getCourseDept()!=null&&!"".equals(coursePCFront.getCourseDept())){
            criteria.andEqualTo("courseDept",coursePCFront.getCourseDept());
        }
        //内部课程
        criteria.andEqualTo("courseType",COURSETYPE);
        //审批通过课程
        criteria.andEqualTo("status",1);
        //授课结束为审批状态
        criteria.andEqualTo("teaStatus",2);
        //排序
        example.setOrderByClause("update_time DESC");
        PageHelper.startPage(coursePCFront.getPage(),coursePCFront.getPageSize());
        Page<Course> pages =(Page<Course>)courseMapper.selectByExample(example);
        List<Course> courses = pages.getResult();
        CoursePCResult coursePCResult = new CoursePCResult();
        CoursePCBack coursePCBack=null;
        List<CoursePCBack> coursePCBacks = coursePCResult.getCoursePCBackList();
        if(courses!=null&&courses.size()>0){
            coursePCResult.setTotals(pages.getTotal());
            for (Course cours : courses) {
                coursePCBack=new CoursePCBack();
                coursePCBack.setId(cours.getId());
                coursePCBack.setTitle(cours.getTitle());
                coursePCBack.setFlag(cours.getFlag());
                coursePCBack.setNum(cours.getNum());
                coursePCBack.setCourseDept(cours.getCourseDept());
                coursePCBack.setUsername(cours.getTeaUsername());
                coursePCBacks.add(coursePCBack);
            }
        }
        return coursePCResult;
    }


    /**
     * 审批授课完成课程
     * @param courseId
     * @param teaStatus
     * @return
     */
    @Override
    public Integer approvalOverCourse(Integer courseId,Integer teaStatus) {
        Course course = new Course();
        course.setId(courseId);
        course.setTeaStatus(teaStatus);
        return courseMapper.updateByPrimaryKeySelective(course);
    }

    /**
     * 查询开课课程
     * @param courseOpenPCFront
     * @return
     */
    @Override
    public CourseOpenPCResult qryCourseOpenResult(CourseOpenPCFront courseOpenPCFront) {
        PageHelper.startPage(courseOpenPCFront.getPage(),courseOpenPCFront.getPageSize());
        Page<CourseOpenPCBack> pages=(Page<CourseOpenPCBack>)courseMapper.selectCourseOpenResult(courseOpenPCFront);
        CourseOpenPCResult courseOpenPCResult = new CourseOpenPCResult();
        courseOpenPCResult.setTotals(pages.getTotal());
        courseOpenPCResult.setCourseOpenPCBacks(pages.getResult());
        return courseOpenPCResult;
    }

    /**
     * 根据id删除课程
     * @param id
     * @return
     */
    @Override
    public Integer deleteCourseOpenById(Integer id) {
        return courseMapper.deleteByPrimaryKey(id);
    }

    /**
     * 批量删除课程
     * @param ids
     * @return
     */
    @Override
    public Integer deleteCourseOpenByIds(List<Integer> ids) {
        return courseMapper.deleteCourseOpenByIds(ids);
    }

    /**
     * 新增课件
     * @param smallCourseFront
     * @return
     */
    @Override
    public Integer insertSmallCourse(SmallCourseFront smallCourseFront) {
        MultipartFile photoFile = smallCourseFront.getPhotoFile();
        if(photoFile==null){
            throw new BusinessRuntimeException(ResultCodeEnum.UPLOAD_ISEMPTY.getCode(),ResultCodeEnum.UPLOAD_ISEMPTY.getMessage());
        }
        MultipartFile multipartFile = smallCourseFront.getMultipartFile();
        if(multipartFile==null){
            throw new BusinessRuntimeException(ResultCodeEnum.UPLOAD_ISEMPTY.getCode(),ResultCodeEnum.UPLOAD_ISEMPTY.getMessage());
        }
        String url=null;
        String fileURL=null;
        //获取文件名
        String fileName=multipartFile.getOriginalFilename();
        //截取文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length()).toLowerCase();
        if(".pdf".equals(fileSuffix)){
            url=ReadPropertiesUtil.readUrl("pdf_url");
            smallCourseFront.setFileType(1);
        }else{
            url= ReadPropertiesUtil.readUrl("video_url");
            smallCourseFront.setFileType(0);
        }
        String photo=null;
        try {
            fileURL = FileTool.upLoad(multipartFile, url);
            photo   = FileTool.upLoad(photoFile,  ReadPropertiesUtil.readUrl("course_photo"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Attachment attachment = new Attachment();
        attachment.setFileType(smallCourseFront.getFileType());
        attachment.setFilePath(fileURL);
        String[] split = fileURL.split("/");
        attachment.setName(split[split.length-1]);
        attachment.setCreateTime(new Date());
        attachmentMapper.insertSelective(attachment);
        Integer annxId = attachment.getId();
        Course course = new Course();
        course.setAnnxId(annxId);
        course.setStatus(1);
        course.setIsOpen(1);
        course.setTitle(smallCourseFront.getName());
        course.setOpenTime(new Date(2099,12,12));
        course.setIntroduce(smallCourseFront.getIntroduce());
        course.setCourseType(2);
        course.setFlag(1);
        course.setUpdateTime(new Date());
        course.setPhoto(photo);
        course.setSmallType(smallCourseFront.getSmallType());
        return courseMapper.insertSelective(course);
    }

    /**
     * 修改微课程
     * @param smallCourseFront
     * @return
     */
    @Override
    public Integer updateSmallCourse(SmallCourseFront smallCourseFront) {
        MultipartFile photoFile = smallCourseFront.getPhotoFile();
        MultipartFile multipartFile = smallCourseFront.getMultipartFile();
        Integer annxId=null;
        String fileURL=null;
        if(multipartFile!=null){
            Integer id = smallCourseFront.getId();
            Course course = courseMapper.selectByPrimaryKey(id);
            annxId = course.getAnnxId();
            String url=null;
            //获取文件名
            String fileName=multipartFile.getOriginalFilename();
            //截取文件后缀
            String fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length()).toLowerCase();
            if("pdf".equals(fileSuffix)){
                url=ReadPropertiesUtil.readUrl("pdf_url");
                smallCourseFront.setFileType(1);
            }else{
                url= ReadPropertiesUtil.readUrl("video_url");
                smallCourseFront.setFileType(0);
            }
            try {
                fileURL = FileTool.upLoad(multipartFile, url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Attachment attachment = new Attachment();
            attachment.setId(annxId);
            attachment.setFileType(smallCourseFront.getFileType());
            attachment.setFilePath(fileURL);
            attachment.setName(smallCourseFront.getName());
            attachmentMapper.updateByPrimaryKeySelective(attachment);
        }

        Course courseUpdate = new Course();
        String photo=null;
        if(photoFile!=null){
            try {
                photo= FileTool.upLoad(photoFile,  ReadPropertiesUtil.readUrl("course_photo"));
                courseUpdate.setPhoto(photo);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        courseUpdate.setSmallType(smallCourseFront.getSmallType());
        courseUpdate.setId(smallCourseFront.getId());
        courseUpdate.setTitle(smallCourseFront.getName());
        courseUpdate.setOpenTime(new Date(2099,12,12));
        courseUpdate.setUpdateTime(new Date());
        return courseMapper.updateByPrimaryKeySelective(courseUpdate);
    }

    /**
     * 新增外部课程
     * @param courseFront
     * @return
     * @throws ParseException
     */
    @Override
    public Integer addOutCourse(CourseOutFront courseFront) throws ParseException{
        MultipartFile photoFile = courseFront.getPhotoFile();
        String photo=null;
        try {
            if(photoFile!=null){
                photo= FileTool.upLoad(photoFile, ReadPropertiesUtil.readUrl("course_photo"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Course course = new Course();
        course.setTitle(courseFront.getTitle());
        course.setSmallTitle(courseFront.getSmallTitle());
        String time=courseFront.getDate()+" "+courseFront.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        course.setOpenTime(df.parse(time));
        course.setAddress(course.getAddress());
        course.setIntroduce(course.getIntroduce());
        course.setStudents(course.getStudents());
        course.setStatus(1);
        course.setFlag(1);
        course.setNum(courseFront.getNum());
        course.setTeaStatus(0);
        course.setIsOpen(1);
        String studentStr="[]";
        Integer studentNum=0;
        course.setStudents(studentStr);
        course.setStudentNum(studentNum);
        course.setTeaId(courseFront.getUserId());
        course.setTeaUsername(userMapper.selectByPrimaryKey(courseFront.getUserId()).getUsername());
        course.setIsOpen(1);
        course.setCourseType(1);
        course.setUpdateTime(new Date());
        course.setIntroduce(courseFront.getIntroduce());
        course.setAddress(courseFront.getAddress());
        course.setCourseDept(1);
        course.setIsGood(courseFront.getIsGood());
        //上课时长
        course.setCourseTime(courseFront.getCourseTime());
        course.setPhoto(photo);
        int result = courseMapper.insertSelective(course);
        Integer id = course.getId();
        String text = ReadPropertiesUtil.readUrl("QRURL")+"?courseId="+id;
        String logoPath =ReadPropertiesUtil.readUrl("logoPath");
        String destPath = ReadPropertiesUtil.readUrl("destPath");
        try {
            String qr = QRCodeUtil.encode(text, logoPath, destPath, true);
            course.setQr(qr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        result=courseMapper.updateByPrimaryKeySelective(course);
        return result;
    }

    /**
     * 修改外部课程
     * @param courseFront
     * @return
     * @throws ParseException
     */
    @Override
    public Integer updateOutCourse(CourseOutFront courseFront) throws ParseException {
        MultipartFile photoFile = courseFront.getPhotoFile();
        String photo=null;
        try {
            if(photoFile!=null){
                photo= FileTool.upLoad(photoFile, ReadPropertiesUtil.readUrl("course_photo"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Course course = new Course();
        course.setTitle(courseFront.getTitle());
        course.setSmallTitle(courseFront.getSmallTitle());
        String time=courseFront.getDate()+" "+courseFront.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        course.setOpenTime(df.parse(time));
        course.setAddress(course.getAddress());
        course.setIntroduce(course.getIntroduce());
        course.setStudents(course.getStudents());
        course.setNum(courseFront.getNum());
        course.setTeaId(courseFront.getUserId());
        course.setTeaUsername(userMapper.selectByPrimaryKey(courseFront.getUserId()).getUsername());
        course.setUpdateTime(new Date());
        course.setIntroduce(courseFront.getIntroduce());
        course.setAddress(courseFront.getAddress());
        course.setCourseDept(1);
        course.setIsGood(courseFront.getIsGood());
        //上课时长
        course.setCourseTime(courseFront.getCourseTime());
        course.setId(courseFront.getId());
        course.setPhoto(photo);
        int result = courseMapper.updateByPrimaryKeySelective(course);
        return result;
    }

    /**
     * 查看微课程
     * @param id
     * @return
     */
    @Override
    public SmallCourseBack qrySmallCourseById(Integer id) {
        return courseMapper.qrySmallCourseById(id);
    }

    /**
     * 根据id查看课程详情
     * @param id
     * @return
     */
    @Override
    public Course qryCourseById(Integer id) {
        return courseMapper.selectByPrimaryKey(id);
    }

    /**
     * 设置精品课程
     * @param id
     * @return
     */
    @Override
    public Integer setGoodCourse(Integer id) {
        Course course = courseMapper.selectByPrimaryKey(id);
        Integer result=0;
        if(course!=null){
            Integer isGood = course.getIsGood();
            if(isGood==0){
                course.setIsGood(1);
            }else{
                course.setIsGood(0);
            }
            result = courseMapper.updateByPrimaryKeySelective(course);
        }
        return result;
    }

    @Resource
    private UserCourseMapper userCourseMapper;
    /**
     * 下载课程评价
     * @param id
     * @return
     */
    @Override
    public String downZipForCourse(Integer id) {
        String zipUrl="";
        Example example = new Example(UserCourse.class);
        example.createCriteria().andEqualTo("courseId",id);
        List<UserCourse> userCourses = userCourseMapper.selectByExample(example);
        if(userCourses!=null&&userCourses.size()>0){
            List<UserCourse> userCourseList = userCourses.stream().filter(x -> x.getUrl() != null).collect(Collectors.toList());
            if(userCourseList!=null&&userCourseList.size()>0){
                List<String> urlStrList=new ArrayList<String>();
                for (UserCourse userCourse : userCourseList) {
                    String url = userCourse.getUrl();
                    url=url.replace(ReadPropertiesUtil.readUrl("excelDIR"),ReadPropertiesUtil.readUrl("excelOutUrl"));
                    urlStrList.add(url);
                }
                Course course = courseMapper.selectByPrimaryKey(id);
                zipUrl = ZipFileTool.fileToZip(urlStrList, ReadPropertiesUtil.readUrl("zipDIR"), course.getTitle() + "-课程评价");
            }else{
                throw new BusinessRuntimeException(ResultCodeEnum.COURSE_EVA_ERROR.getCode(),ResultCodeEnum.COURSE_EVA_ERROR.getMessage());
            }
        }else {
            throw new BusinessRuntimeException(ResultCodeEnum.COURSE_ERROR.getCode(),ResultCodeEnum.COURSE_ERROR.getMessage());
        }
        return zipUrl;
    }

    /**
     * 批量导入课程
     * @param multipartFile
     * @return
     */
    @Override
    public String importCourse(MultipartFile multipartFile) {
        Integer count=0;
        List<List<Object>> bankListByExcel=new ArrayList<List<Object>>();
        try{
            bankListByExcel= ExcelUtils.getBankListByExcel(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
        }catch (Exception e){
            throw new BusinessRuntimeException(ResultCodeEnum.EXCEL_ERROR.getCode(),ResultCodeEnum.EXCEL_ERROR.getMessage());
        }
        if(bankListByExcel.size()<1){
            throw new BusinessRuntimeException(ResultCodeEnum.EXCEL_EMPTY.getCode(),ResultCodeEnum.EXCEL_EMPTY.getMessage());
        }
        List<Course> courses = new ArrayList<>();
        Course course=null;
        for(int i=0;i<bankListByExcel.size();i++){
            course=new Course();
            course.setTeaUsername((String) bankListByExcel.get(i).get(1));
            course.setTitle((String) bankListByExcel.get(i).get(2));
            course.setSmallTitle((String)bankListByExcel.get(i).get(3));
            String courseTimeStr=(String) bankListByExcel.get(i).get(4);
            try{
                int courseTime = Integer.parseInt(courseTimeStr);
                course.setCourseTime(courseTime);
                String openTimeStr=(String)bankListByExcel.get(i).get(5);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Date date = df.parse(openTimeStr);
                Date newDate = new Date();
                if(newDate.after(date)){
                    course.setTeaStatus(0);
                }else {
                    course.setTeaStatus(1);
                }
                course.setOpenTime(date);
                String address=(String)bankListByExcel.get(i).get(6);
                course.setAddress(address);
                String numStr=(String)bankListByExcel.get(i).get(7);
                int num = Integer.parseInt(numStr);
                course.setNum(num);
                course.setIntroduce((String)bankListByExcel.get(i).get(8));
                course.setDdId((String) bankListByExcel.get(i).get(9));
                course.setIsOpen(1);
                String isGoodStr=(String) bankListByExcel.get(i).get(10);
                int isGood = Integer.parseInt(isGoodStr);
                course.setIsGood(isGood);
                course.setFlag(1);
                course.setStatus(1);
                course.setCourseType(0);
                course.setCourseDept(1);
                course.setUpdateTime(new Date());
            }catch (Exception e){
                continue;
            }
            courses.add(course);
        }
        if(courses.size()<1){
            return "导入失败";
        }
        List<String> ddIds = courses.stream().map(x -> x.getDdId()).collect(Collectors.toList());
        Example example = new Example(User.class);
        example.createCriteria().andIn("userId",ddIds);
        List<User> users = userMapper.selectByExample(example);
        if(users.size()<1){
            return "导入失败";
        }
        List<Course> courseToDbs=new ArrayList<Course>();
        for (Course cours : courses) {
            for (User user : users) {
                if(cours.getDdId().equals(user.getUserId())){
                    cours.setTeaId(user.getId());
                    cours.setDeptId(user.getDeptId());
                    courseToDbs.add(cours);
                }
            }
        }
        if(courseToDbs.size()<1){
            return "导入失败";
        }
        for (Course courseToDb : courseToDbs) {
            courseMapper.insertSelective(courseToDb);
            Integer id = courseToDb.getId();
            String text = ReadPropertiesUtil.readUrl("QRURL")+"?courseId="+id;
            String logoPath =ReadPropertiesUtil.readUrl("logoPath");
            String destPath = ReadPropertiesUtil.readUrl("destPath");
            try {
                String qr = QRCodeUtil.encode(text, logoPath, destPath, true);
                courseToDb.setQr(qr);
            } catch (Exception e) {
                courseMapper.deleteByPrimaryKey(id);
                continue;
            }
            courseMapper.updateByPrimaryKeySelective(courseToDb);
            count++;
        }
        Integer fail=bankListByExcel.size()-count;
        if(fail>0){
            return "成功导入："+count+"条,失败"+fail+"条";
        }
        return  "成功导入："+count+"条";
    }


}
